<template>
  <el-affix v-if="affixed" :offset="affixOffset">
    <div class="search-form-container">
      <div class="search-form-content">
        <!-- 自定义操作区域 -->
        <div class="search-form-actions">
          <slot name="actions"></slot>
        </div>

        <el-form
          ref="formRef"
          class="search-form"
          :inline="true"
          :label-width="showLabel ? labelWidth : '0px'"
          :model="state.form"
          :size="size"
          @submit.prevent="handleSearch"
        >
          <div class="form-main-container">
            <div class="form-fields-wrapper" :class="{ 'is-collapsed': isCollapsed && hasHiddenFields }">
              <div
                v-for="(field, index) in visibleFields"
                :key="field.prop"
                class="form-field-item"
                :class="[
                  field.colSpan ? `col-span-${field.colSpan}` : '',
                  `sm:w-full md:w-auto`,
                  { 'hidden-field': isCollapsed && index >= visibleItemsCount },
                ]"
              >
                <el-form-item :label="showLabel ? field.label : ''" :prop="field.prop" :rules="field.rules">
                  <!-- 使用具名插槽支持自定义渲染 -->
                  <slot :field="field" :name="field.prop">
                    <!-- 输入框 -->
                    <el-input
                      v-if="field.component === 'input'"
                      v-model="state.form[field.prop]"
                      v-bind="field.componentProps || {}"
                      clearable
                      :disabled="field.disabled"
                      :placeholder="field.placeholder || field.label"
                      @keyup.enter="handleSearch"
                    />
                    <!-- 选择器 -->
                    <el-select
                      v-else-if="field.component === 'select'"
                      v-model="state.form[field.prop]"
                      v-bind="field.componentProps || {}"
                      clearable
                      :disabled="field.disabled"
                      filterable
                      :multiple="field.componentProps?.multiple"
                      :placeholder="field.placeholder || field.label"
                    >
                      <el-option
                        v-for="option in field.options || field.componentProps?.options"
                        :key="option.value"
                        :disabled="option.disabled"
                        :label="option.label"
                        :value="option.value"
                      />
                    </el-select>
                    <!-- 日期选择器 -->
                    <el-date-picker
                      v-else-if="field.component === 'date' || field.component === 'date-picker'"
                      v-model="state.form[field.prop]"
                      v-bind="field.componentProps || {}"
                      clearable
                      :disabled="field.disabled"
                      :placeholder="field.placeholder || field.label"
                    />
                    <!-- 动态组件 -->
                    <component
                      :is="field.component"
                      v-else
                      v-model="state.form[field.prop]"
                      v-bind="field.componentProps || {}"
                      :disabled="field.disabled"
                      :placeholder="field.placeholder || field.label"
                    />
                  </slot>
                </el-form-item>
              </div>
            </div>

            <div class="form-actions">
              <el-button class="search-btn" :loading="state.loading" type="primary" @click="handleSearch">
                <el-icon><el-icon-search /></el-icon>
                查询
              </el-button>
              <el-button class="reset-btn" @click="handleReset">
                <el-icon><el-icon-refresh /></el-icon>
                重置
              </el-button>

              <!-- 折叠/展开按钮 -->
              <el-button v-if="hasHiddenFields" class="expand-btn" text type="primary" @click="toggleCollapse">
                {{ isCollapsed ? '展开' : '收起' }}
                <el-icon :class="{ 'is-reverse': !isCollapsed }">
                  <el-icon-arrow-down />
                </el-icon>
              </el-button>
            </div>
          </div>
        </el-form>
      </div>
    </div>
  </el-affix>

  <div v-else class="search-form-container">
    <div class="search-form-content">
      <!-- 自定义操作区域 -->
      <div class="search-form-actions">
        <slot name="actions"></slot>
      </div>

      <el-form
        ref="formRef"
        class="search-form"
        :inline="true"
        :label-width="showLabel ? labelWidth : '0px'"
        :model="state.form"
        :size="size"
        @submit.prevent="handleSearch"
      >
        <div class="form-main-container">
          <div class="form-fields-wrapper" :class="{ 'is-collapsed': isCollapsed && hasHiddenFields }">
            <div
              v-for="(field, index) in visibleFields"
              :key="field.prop"
              class="form-field-item"
              :class="[
                field.colSpan ? `col-span-${field.colSpan}` : '',
                `sm:w-full md:w-auto`,
                { 'hidden-field': isCollapsed && index >= visibleItemsCount },
              ]"
            >
              <el-form-item :label="showLabel ? field.label : ''" :prop="field.prop" :rules="field.rules">
                <!-- 使用具名插槽支持自定义渲染 -->
                <slot :field="field" :name="field.prop">
                  <!-- 输入框 -->
                  <el-input
                    v-if="field.component === 'input'"
                    v-model="state.form[field.prop]"
                    v-bind="field.componentProps || {}"
                    clearable
                    :disabled="field.disabled"
                    :placeholder="field.placeholder || field.label"
                    @keyup.enter="handleSearch"
                  />
                  <!-- 选择器 -->
                  <el-select
                    v-else-if="field.component === 'select'"
                    v-model="state.form[field.prop]"
                    v-bind="field.componentProps || {}"
                    clearable
                    :disabled="field.disabled"
                    filterable
                    :multiple="field.componentProps?.multiple"
                    :placeholder="field.placeholder || field.label"
                  >
                    <el-option
                      v-for="option in field.options || field.componentProps?.options"
                      :key="option.value"
                      :disabled="option.disabled"
                      :label="option.label"
                      :value="option.value"
                    />
                  </el-select>
                  <!-- 日期选择器 -->
                  <el-date-picker
                    v-else-if="field.component === 'date' || field.component === 'date-picker'"
                    v-model="state.form[field.prop]"
                    v-bind="field.componentProps || {}"
                    clearable
                    :disabled="field.disabled"
                    :placeholder="field.placeholder || field.label"
                  />
                  <!-- 动态组件 -->
                  <component
                    :is="field.component"
                    v-else
                    v-model="state.form[field.prop]"
                    v-bind="field.componentProps || {}"
                    :disabled="field.disabled"
                    :placeholder="field.placeholder || field.label"
                  />
                </slot>
              </el-form-item>
            </div>
          </div>

          <div class="form-actions">
            <el-button class="search-btn" :loading="state.loading" type="primary" @click="handleSearch">
              <el-icon><el-icon-search /></el-icon>
              查询
            </el-button>
            <el-button class="reset-btn" @click="handleReset">
              <el-icon><el-icon-refresh /></el-icon>
              重置
            </el-button>

            <!-- 折叠/展开按钮 -->
            <el-button v-if="hasHiddenFields" class="expand-btn" text type="primary" @click="toggleCollapse">
              {{ isCollapsed ? '展开' : '收起' }}
              <el-icon :class="{ 'is-reverse': !isCollapsed }">
                <el-icon-arrow-down />
              </el-icon>
            </el-button>
          </div>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ArrowDown as ElIconArrowDown, Refresh as ElIconRefresh, Search as ElIconSearch } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import { computed, ref, watch } from 'vue'
import { useSearchForm } from './hooks/useSearchForm'
import type { SearchFormOptions } from './types'

const props = withDefaults(defineProps<SearchFormOptions & { showLabel?: boolean }>(), {
  fields: () => [],
  loading: false,
  inline: true,
  labelWidth: '0px', // 默认不显示标签
  labelPosition: 'right',
  size: 'default',
  affixed: true,
  affixOffset: 66,
  showLabel: false, // 默认不显示标签
})

const emit = defineEmits(['update:modelValue', 'form-change', 'search', 'reset'])

const formRef = ref<FormInstance>()
const { state, resetForm, setForm, setLoading } = useSearchForm(props.fields)

// 可见字段
const visibleFields = computed(() => {
  return props.fields.filter((field) => field.visible !== false)
})

// 折叠相关逻辑
const isCollapsed = ref(true)
const visibleItemsCount = 3 // 默认显示的字段数量

// 是否有需要隐藏的字段
const hasHiddenFields = computed(() => {
  return visibleFields.value.length > visibleItemsCount
})

// 切换折叠状态
const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value
}

// 监听 loading 状态
watch(
  () => props.loading,
  (val) => {
    setLoading(val)
  }
)

// 监听 modelValue 变化，更新表单数据
watch(
  () => props.modelValue,
  (newValue) => {
    if (newValue) {
      // 使用临时对象进行比较，避免不必要的更新
      const hasChanged = Object.keys(newValue).some((key) => state.form[key] !== newValue[key])
      if (hasChanged) {
        setForm(newValue)
      }
    }
  },
  { immediate: true, deep: true }
)

// 监听表单数据变化，更新 modelValue
watch(
  () => state.form,
  (newValue) => {
    // 使用临时对象进行比较，避免不必要的更新
    const hasChanged = Object.keys(newValue).some((key) => props.modelValue[key] !== newValue[key])
    if (hasChanged) {
      emit('update:modelValue', { ...newValue })
      emit('form-change', { ...newValue })
    }
  },
  { deep: true }
)

// 搜索
const handleSearch = () => {
  emit('search')
}

// 重置
const handleReset = () => {
  resetForm()
  emit('reset')
}

// 暴露方法
defineExpose({
  formRef,
  setForm,
  resetForm,
})
</script>

<style lang="scss" scoped>
.search-form-container {
  background: #fff;
  margin-bottom: 20px;
  border-radius: 12px;
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.03);
  transition: all 0.3s;

  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  }
}

.search-form-content {
  padding: 16px;
  display: flex;
  flex-direction: column;
}

.search-form-actions {
  margin-bottom: 16px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.search-form {
  width: 100%;

  .form-main-container {
    display: flex;
    align-items: flex-start;
    width: 100%;

    @media (max-width: 768px) {
      flex-direction: column;
    }

    @media (min-width: 769px) {
      flex-direction: row;
      flex-wrap: nowrap;
    }
  }

  .form-fields-wrapper {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    flex: 1;
    transition: max-height 0.3s ease;
    overflow: hidden;

    &.is-collapsed {
      max-height: 60px;
    }
  }

  .form-field-item {
    transition: all 0.3s;
    min-width: 220px;
    flex-shrink: 0;

    &.hidden-field {
      display: none;
    }

    @media (max-width: 768px) {
      width: 100% !important;
    }

    @media (min-width: 769px) {
      width: auto !important;
    }
  }

  :deep(.el-form-item) {
    margin-bottom: 8px;
    margin-right: 0;
    width: 100%;
  }

  :deep(.el-form-item__content) {
    justify-content: flex-start;
    width: 100%;
  }

  :deep(.el-input) {
    width: 100%;
    min-width: 180px;
  }

  :deep(.el-select) {
    width: 100%;
    min-width: 180px;
  }

  :deep(.el-date-editor) {
    width: 100%;
    min-width: 220px;
  }

  :deep(.el-input__inner) {
    border-radius: 6px;
    transition: all 0.2s;
  }
}

.form-actions {
  display: flex;
  align-items: center;
  gap: 8px;
  padding-left: 12px;
  white-space: nowrap;

  @media (max-width: 768px) {
    margin-top: 12px;
    padding-left: 0;
  }

  .el-button {
    margin-right: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 4px;
  }

  .search-btn,
  .reset-btn {
    padding: 8px 16px;
    border-radius: 6px;
    transition: all 0.25s ease;
  }

  .expand-btn {
    .el-icon {
      transition: transform 0.3s;

      &.is-reverse {
        transform: rotate(180deg);
      }
    }
  }
}
</style>
